import { Table } from 'antd';
import { FC, useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useWindowSize } from 'react-use';

export interface DataType {
  data: any;
  total: number;
}

interface TableProps {
  columnData: any;
  getData: any; //  (data: any) => DataType; // 获取表格数据函数
  filterName?: string; // 筛选名称
  refresh?: boolean; // 刷新
}

const TableComponent: FC<TableProps> = ({ columnData, getData, filterName, refresh }) => {
  const id = useParams().id;
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(1);
  const [dataSource, setDataSource] = useState<any>([]);
  const [page, setPage] = useState(1);
  const { width, height } = useWindowSize();
  const [scrollY, setScroll] = useState<number>();
  const [filterInfo, setFilterInfo] = useState<any>({});
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    if (width && height) {
      setScroll(height - 300);
    }
  }, [height, width]);

  const getDataList = async () => {
    setLoading(true);
    const requestQuery: any = {
      page_num: page,
      page_size: pageSize
    };
    if (filterName) requestQuery.name = filterName;
    const data = await getData({ ...requestQuery, ...filterInfo }, columnData);
    setLoading(false);
    setDataSource(data.data);
    setTotal(data.total);
    return data;
  };

  useEffect(() => {
    if (page == 0) getDataList();
    else setPage(1);
  }, [filterName]);

  useEffect(() => {
    getDataList();
  }, [filterInfo, pageSize, page, refresh, id, columnData]);

  const pageChangeHandle = (page: number, pageSize: number | undefined) => {
    if (pageSize) {
      setPageSize(pageSize);
    }
    setPage(page);
  };

  const onTableChangeHandler = (pagetion: any, filter: any, sorter: any, extra: any) => {
    setFilterInfo({ ...filter, page_num: pagetion.current });
    if (extra.action !== 'paginate') setPage(1);
  };

  useEffect(() => {
    setPage(1);
    setFilterInfo({ ...filterInfo, page_num: 1 });
  }, [id]);

  return (
    <Table
      scroll={{ x: '100%', y: scrollY }}
      columns={columnData}
      dataSource={dataSource}
      rowKey={row => row.id}
      loading={loading}
      onChange={onTableChangeHandler}
      pagination={{
        showQuickJumper: true,
        showSizeChanger: true,
        pageSize: pageSize,
        pageSizeOptions: ['10', '20', '50', '100'],
        total: total,
        current: page,
        onChange: pageChangeHandle,
        showTotal: () => <div>共{total}条</div>
      }}
    />
  );
};

export default TableComponent;
